<!--
  单个颜色主题
  跟coverPopover-new差不多
  颜色主题块 + popover效果
-->
<template>
  <div :class="`color-theme ${action ? action : ''}`">
    <el-popover
      v-if="action !== 'new'"
      placement="top-start"
      width="200"
      trigger="click"
      :popper-class="popTheme"
    >
      <div class="popover_cont">
        <div class="action">
          <el-button
            :link="true"
            type="primary"
            icon="EditPen"
            size="default"
            :title="$demoi18n('btn.edit')"
            @click="editTheme"
          ></el-button>
          <el-button
            :link="true"
            type="primary"
            icon="Delete"
            size="default"
            :title="$demoi18n('btn.delete')"
            @click="delTheme"
          ></el-button>
          <i
            v-if="isShowResetBtn"
            class="reset vs_icon_dev vs_icon_dev_huifuchuchangshezhi"
            :title="$demoi18n('btn.reset')"
            @click="resetTheme"
          ></i>
        </div>
        <div class="swatches">
          <span
            v-for="(item, index) in getThemeColors(theme)"
            :key="index"
            :style="getBackground(item)"
          ></span>
        </div>
      </div>
      <template #reference>
        <div
          class="inner"
          :style="colorThemeStyle"
        >
          <ColorBlock
            :colors="getThemeColors(theme)"
            :size="size"
          />
        </div>
      </template>
    </el-popover>
    <div v-else>
      <div
        class="inner"
        :style="colorThemeStyle"
        @click="addNewTheme"
      >
        <ColorBlock
          type="new"
          :size="size"
        />
      </div>
    </div>
    <!-- 正常的颜色组件 -->
    <ColorThemeEditor
      :config="config"
      :form="form"
      :visible="editorVisable && !form.colorComponents"
      :theme-conf="theme"
      @save="saveTheme"
      @cancel="cancelEditTheme"
    />
    <!-- 颜色关联组件,可自定义字段与颜色之间的关系 -->
    <ColorThemeEditorCustom
      :config="config"
      :form="form"
      :visible="editorVisable && form.colorComponents === 'ColorThemeEditorCustom'"
      :theme-conf="theme"
      :enum-prikey="enumPrikey"
      @save="saveTheme"
      @cancel="cancelEditTheme"
    />
    <!-- 多级排行-定制颜色组件 -->
    <ColorThemeEditorMultiRank
      :config="config"
      :form="form"
      :visible="editorVisable && form.colorComponents === 'ColorThemeEditorMultiRank'"
      :theme-conf="theme"
      @save="saveTheme"
      @cancel="cancelEditTheme"
    />
  </div>
</template>
<script>
import ColorBlock from './color-block.vue';
import ColorThemeEditor from './color-theme-editor.vue';
import ColorThemeEditorCustom from './color-theme-editor-custom.vue';
import ColorThemeEditorMultiRank from './color-theme-editor-multl-rank';
import { dateFormat, $confirm } from '@/utils/util.js';

function getEmptyThemeConf(conf) {
  return {
    componentStyle: conf ? conf.componentStyle : '',
    type: conf ? conf.type : '', // single | gradient,
    key: `t${dateFormat('yyyyMMddhhmmssS', new Date())}`, // t20200907173055021

    colors: [],
  };
}

export default {
  components: {
    ColorBlock,
    ColorThemeEditor,
    ColorThemeEditorCustom,
    ColorThemeEditorMultiRank,
  },
  props: {
    config: Object, // 组件的全部配置
    form: Object, // 对应具体组件的property
    action: String, // 新增颜色时传'new'，编辑时不需要传或传'edit'
    componentStyle: String, // light | dark,   action传new是需要传
    type: String, // single | gradient,  action传new是需要传
    isChecked: {

      // 是否选中状态
      type: Boolean,
      default: false,
    },
    enumPrikey: String, // 自定义颜色主题下拉选择字段名

    themeConf: {
      type: Object,
      default: () => getEmptyThemeConf(),
    },
  },
  emits: ['resetTheme', 'saveNewTheme', 'delTheme'],
  data() {
    const _themeConf = JSON.parse(JSON.stringify(this.themeConf));
    return {
      xvueTheme: window._adoPremise.uc.theme,
      size: 20,
      editorVisable: false,
      theme: _themeConf,
    };
  },
  computed: {
    popTheme() {
      return `color-theme-popover color-theme-popover-${window._adoPremise.uc.theme || 'light'}`;
    },
    colorThemeStyle() {
      const style = {
        width: `${this.size + 2}px`,
        height: `${this.size + 2}px`,
      };
      if (this.isChecked) {
        style.border = '1px solid #409EFF';
      }
      return style;
    },
    isShowResetBtn() {
      return !/^t\d+/.test(this.themeConf.key);
    },
  },
  watch: {
    themeConf: {
      handler(newVal) {
        this.theme = JSON.parse(JSON.stringify(newVal));
      },
      deep: true,
    },
  },
  methods: {
    getThemeColors(theme) {
      const originalContent = theme[`${theme.colorType}_original_content`];
      if (!originalContent.length) {
        return theme.colors;
      } else {
        return originalContent;
      }
    },
    getBackground(item) {
      if (Array.isArray(item) && item.length >= 2) {
        return {
          background: `linear-gradient(to right, ${item[0]}, ${item[1]})`,
        };
      } else if (item && typeof item === 'string') {
        return {
          background: `${item}`,
        };
      } else {}
      return {};
    },
    addNewTheme() {
      this.theme = {
        type: this.type,
        componentStyle: this.componentStyle,
        key: `t${dateFormat('yyyyMMddhhmmssS', new Date())}`,
        colors: this.type === 'single' ? ['#dddddd'] : [['#dddddd', '#dddddd']],
        colorType: this.type, // 'single'
        colorContentSource: 'original',
        'single_original_content': [],
        'single_custom_content': [],
        'gradient_original_content': [],
        'gradient_custom_content': [],
      };
      this.editorVisable = true;
    },
    editTheme() {
      this.editorVisable = true;
    },
    resetTheme() {
      $confirm(this.$demoi18n('panel.colorTheme.resetConfirm'), this.$demoi18n('popup.title.tips'), {
        confirmButtonText: this.$demoi18n('btn.confirm'),
        cancelButtonText: this.$demoi18n('btn.cancel'),
        type: 'warning',
      }).then(() => {
        this.$emit('resetTheme', this.themeConf);
      });
    },
    saveTheme(themeConf, type) {
      this.editorVisable = false;
      if (this.action === 'new') {
        const _themeConf = JSON.parse(JSON.stringify(themeConf));
        this.$emit('saveNewTheme', _themeConf);
      } else {
        Object.entries(this.themeConf).map(([i]) => {
          // 内存地址不变，属性改变
          this.themeConf[i] = themeConf[i];
        });

        // type为ColorThemeEditorMultiRank的特殊处理
        if (type === 'ColorThemeEditorMultiRank') {
          this.themeConf['multi_rank_content'] = themeConf.multi_rank_content;
        }
        this.theme = JSON.parse(JSON.stringify(this.themeConf));
      }
    },
    cancelEditTheme() {
      this.editorVisable = false;
    },
    delTheme() {
      this.$emit('delTheme', this.themeConf);
    },
  },
};
</script>
<style lang="less">
.color-theme-popover {
  width: max-content !important;
  min-width: unset;
  padding: 6px 3px;
  line-height: 1;
  box-shadow: 1px 1px 4px #868686;
}
.color-theme-popover-dark {
  background: #064559;
  border-color: #064559;
  .popper__arrow {
    display: none;
  }
}
</style>
<style lang="less" scoped>
.color-theme {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  .inner {
    border: 1px solid #ddd;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.popover_cont {
  max-width: 200px;
  .swatches {
    span {
      display: inline-block;
      width: 12px;
      height: 12px;
      margin: 3px 3px;
    }
  }
  .action {
    display: flex;
    align-items: center;
    .el-button {
      margin: 0 2px;
    }
    .reset {
      cursor: pointer;
      color: #409eff;
      margin-left: 1px;
      font-size: 16px;
      &:hover {
        color: #7dbdff;
      }
    }
  }
}
</style>
